import { getMessageList, getUserMessageList } from '@/api/marketers/message/message';
import { useMessage } from '@/stores/counter';
import myCookies from '@/utils/myCookies';
import { Chat, Radio, RadioGroup } from '@kousum/semi-ui-vue';
import { defineComponent, onMounted, ref } from 'vue';

const ws = ref();
const token = myCookies.getToken();


const commonOuterStyle = {
  border: '1px solid var(--semi-color-border)',
  borderRadius: '16px',
  margin: '8px 16px',
  height: '550px',
}
let id = 0;

function getId() {
  return `id-${id++}`
}

const uploadProps = { action: 'https://api.semi.design/upload' }
const uploadTipProps = { content: '自定义上传按钮提示信息' }

const DefaultChat = defineComponent(() => {
  const mode = ref<"bubble" | "noBubble" | "userBubble">('bubble');
  const align = ref<"leftRight" | "leftAlign">('leftRight');
// 初始化 WebSocket 连接
  if (token != undefined) {
      ws.value = new WebSocket(
          `/chat?token=${encodeURIComponent(token)}`
      ); // 替换为你的 WebSocket 地址
  }

  // 监听连接打开
  ws.value.onopen = async () => {
      console.log("WebSocket 连接已建立");
  };

  // 监听消息接收
  ws.value.onmessage = async (event: any) => {

    const eventData =  JSON.parse(event.data)
    console.log(eventData)
    const newAssistantMessage = {
      role: 'duifang',
      id: getId(),
      createAt: Date.now(),
      content: eventData.data,
    }

    setTimeout(() => {
      if(useMessage().userId === eventData.userId){      useMessage().message = [...useMessage().message, newAssistantMessage]}
    }, 200);
    const tabsUser = useMessage().editableTabs.filter(item=>{return item.userId===eventData.userId })
    if(tabsUser.length ==0){    
      await getMessageList().then((response) => {
      useMessage().editableTabs = response.data.data;
    });}

  };

  // 监听错误
  ws.value.onerror = (error: any) => {
      console.error("WebSocket 错误:", error);
  };

  // 监听连接关闭
  ws.value.onclose = () => {
      console.log("WebSocket 连接已关闭");
  };

  const onAlignChange = (e:any) => {
    align.value = (e.target.value);
  };

  const onModeChange = (e:any) => {
    mode.value = (e.target.value);
  };
  // 发送消息时触发
  const onMessageSend = (content: any, attachment: any) => {
    console.log(useMessage().userId)
    ws.value.send(JSON.stringify({content:content,toUserId:useMessage().userId,time: new Date()}));
  };

  const onChatsChange = (chats:any) => {
    console.log(chats)
    useMessage().message = chats;
  };

  const onMessageReset = (e:any) => {
    console.log(e)
    setTimeout(() => {
      const lastMessage = useMessage().message[useMessage().message.length - 1];
      const newLastMessage = {
        ...lastMessage,
        status: 'complete',
        content: 'This is a mock reset message.',
      }
      useMessage().message = [...useMessage().message.slice(0, -1), newLastMessage]
    }, 200);
  }

  return () => (
    <>
    <span style= {{ display: 'flex', flexDirection: 'column', rowGap: '8px' }
}>
<span style={{ display: 'flex', alignItems: 'center', columnGap: '10px' }}>
  模式
  < RadioGroup onChange = { onModeChange } value = { mode.value } type = { "button"} >
    <Radio value={ 'bubble' }> 气泡 </Radio>
      < Radio value = { 'noBubble'} > 非气泡 </Radio>
        < Radio value = { 'userBubble'} > 用户会话气泡 </Radio>
          </RadioGroup>
          </span>
          < span style = {{ display: 'flex', alignItems: 'center', columnGap: '10px' }}>
            会话对齐方式
            < RadioGroup onChange = { onAlignChange } value = { align.value } type = { "button"} >
              <Radio value={ 'leftRight' }> 左右分布 </Radio>
                < Radio value = { 'leftAlign'} > 左对齐 </Radio>
                  </RadioGroup>
                  </span>
                  </span>
                  < Chat
key = { align.value + mode.value }
align = { align.value }
mode = { mode.value }
uploadProps = { uploadProps }
style = { commonOuterStyle }
chats = { useMessage().message }
roleConfig = { useMessage().roleInfo }
onChatsChange = { onChatsChange }
onMessageSend = { onMessageSend }
onMessageReset = { onMessageReset }
uploadTipProps = { uploadTipProps }
  />
  </>
  )
})

export default DefaultChat